#!/bin/bash

if [ $# -lt 1 ]; then
    echo "$0 <pid>"
    exit 1
fi

total_old=0
tm=0
tm_old=0
per=0

function clocks()
{
    PID=$1

    data=$(awk '{print $14,$15}' /proc/$PID/stat)
    tm=$(date "+%s.%3N")
    user=$(echo $data | awk '{print $1}')
    sys=$(echo $data | awk '{print $2}')

    total=$((user + sys))
    ret=$((total - total_old))
    total_old=$total
    et=$(echo "${tm} - ${tm_old}" | bc)
    tm_old=$tm
    per=$(echo "scale=3; $ret / $et" | bc)
}


while true

do
    clocks $1
    echo "cpu usage of pid $1: $per %"
    sleep 0.1

done

